import React, { useState, useRef, useEffect } from 'react';
import { Card, Form, Table, Divider } from 'antd';
import type { FormInstance } from 'antd';
import type { ResultItem } from '../../../shared/types';
import CalcControls from './CalcControls';
import { renderLatex } from '../../utils/renderLatex';

/**
 * 计算卡片组件属性接口定义
 * 
 * 该接口定义了计算卡片组件所需的所有属性，包括：
 * - 基本显示属性（标题、初始值等）
 * - 表单相关属性（表单实例、表单字段等）
 * - 计算相关属性（计算结果、计算方法等）
 * - UI相关属性（列数、表格高度等）
 */
interface CalculationCardProps {
  title: string;
  form?: FormInstance<any>;
  initialValues: any;
  renderFormFields: () => React.ReactNode;
  result: ResultItem[];
  onCalculate: () => void;
  onReset: () => void;
  columns: any[];
  columnCount?: number; // 添加自定义列数支持
  tableHeight?: number; // 添加表格高度支持
  // optional ref to expose the active form instance to parent; use a simple shape to avoid MutableRefObject deprecation
  formRef?: { current: FormInstance<any> | null } | null;
  formula?: string; // 添加公式支持
  isCalculating?: boolean; // 计算状态指示器
  exportComponent?: React.ReactNode; // 导出组件
  onValuesChange?: (changedValues: any, allValues: any) => void; // 表单值变化回调
}

// 使用统一的renderLatex函数

/**
 * 通用计算卡片组件
 * 
 * 该组件提供了一个完整的计算界面，包括：
 * 1. 参数输入表单区域
 * 2. 计算控制按钮区域
 * 3. 结果展示表格区域
 * 4. 数据导入导出工具栏
 * 5. 数学公式展示区域
 * 
 * 组件特性：
 * - 响应式布局，支持桌面和移动设备
 * - 可调整的分隔面板
 * - 支持数学公式渲染
 * - 集成数据导入导出功能
 * - 支持自定义列数和表格高度
 */
const CalculationCard: React.FC<CalculationCardProps> = ({
  title,
  form,
  formRef,
  initialValues,
  renderFormFields,
  result,
  onCalculate,
  onReset,
  columns,
  columnCount = 1, // 默认1列
  tableHeight = 400, // 默认高度400px
  formula, // 公式内容
  isCalculating = false, // 计算状态，默认为false
  exportComponent, // 导出组件
  onValuesChange // 表单值变化回调
}) => {
  // 分隔面板的状态和引用
  const [splitRatio, setSplitRatio] = useState(50);
  const [isHovering, setIsHovering] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const splitterRef = useRef<HTMLDivElement>(null);
  const isDragging = useRef(false);
  const startX = useRef(0);
  const startRatio = useRef(0);

  // 处理分隔条拖动开始
  const handleMouseDown = (e: React.MouseEvent) => {
    isDragging.current = true;
    startX.current = e.clientX;
    startRatio.current = splitRatio;
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    document.body.style.cursor = 'col-resize';
  };

  // 处理分隔条拖动中
  const handleMouseMove = (e: MouseEvent) => {
    if (!isDragging.current || !containerRef.current) return;
    
    const containerWidth = containerRef.current.offsetWidth;
    const deltaX = e.clientX - startX.current;
    const newRatio = startRatio.current + (deltaX / containerWidth) * 100;
    
    // 限制最小和最大比例
    const clampedRatio = Math.max(30, Math.min(70, newRatio));
    setSplitRatio(clampedRatio);
  };

  // 处理分隔条拖动结束
  const handleMouseUp = () => {
    isDragging.current = false;
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
    document.body.style.cursor = 'default';
  };

  // 处理窗口大小变化和响应式布局
  const [isMobile, setIsMobile] = useState(false);
  
  useEffect(() => {
    const handleResize = () => {
      // 检测屏幕宽度，设置是否为移动设备
      const isSmallScreen = window.innerWidth < 768;
      setIsMobile(isSmallScreen);
      
      // 在小屏幕上设置固定比例
      if (isSmallScreen) {
        setSplitRatio(100);
      } else if (splitRatio === 100) {
        setSplitRatio(50); // 恢复默认比例
      }
    };

    // 初始化时检查屏幕大小
    handleResize();
    
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [splitRatio]);

  // Use provided form or create internal one
  const internalForm = Form.useForm()[0];
  const usedForm = form ?? internalForm;

  // expose form via ref if provided
  React.useEffect(() => {
    if (formRef) formRef.current = usedForm;
    return () => {
      if (formRef) formRef.current = null;
    };
  }, [formRef, usedForm]);

  return (
    <div ref={containerRef} style={{ marginBottom: '24px' }}>
        {isMobile ? (
          // 移动设备布局 - 垂直堆叠
          <div style={{ display: 'block' }}>
            {/* 参数卡片 */}
            <div style={{ marginBottom: '16px' }}>
              <Card title={`${title}参数`}>
                <Form
                  form={usedForm}
                  initialValues={initialValues}
                  layout="vertical"
                  onValuesChange={onValuesChange}
                >
                  {formula && (
                    <div dangerouslySetInnerHTML={renderLatex(formula)} />
                  )}
                  {formula && <Divider style={{ margin: '16px 0' }} />}
                  <div style={{ 
                    display: 'grid', 
                    gridTemplateColumns: `repeat(${columnCount}, 1fr)`,
                    gap: '16px'
                  }}>
                    {renderFormFields()}
                  </div>
                  <Form.Item>
                    <div style={{ marginBottom: 16 }}>
                      <CalcControls
                        onCalculate={onCalculate}
                        onReset={onReset}
                        exportComponent={exportComponent}
                        disabled={isCalculating}
                      />
                    </div>
                  </Form.Item>
                </Form>
              </Card>
            </div>
            
            {/* 结果卡片 */}
            <div>
              <Card title={`${title}结果`}>
                <Table
                  dataSource={result}
                  columns={columns}
                  pagination={false}
                  bordered
                  rowKey="key"
                  scroll={{ y: tableHeight }}
                />
              </Card>
            </div>
          </div>
        ) : (
          // 桌面设备布局 - 水平分隔
          <div style={{ display: 'flex', height: '100%' }}>
            {/* 参数卡片 */}
            <div style={{ width: `${splitRatio}%`, overflow: 'hidden' }}>
              <Card title={`${title}参数`} style={{ height: '100%', marginRight: '4px' }}>
                <Form
                  form={usedForm}
                  initialValues={initialValues}
                  layout="vertical"
                  onValuesChange={onValuesChange}
                >
                  {formula && (
                    <div dangerouslySetInnerHTML={renderLatex(formula)} />
                  )}
                  {formula && <Divider style={{ margin: '16px 0' }} />}
                  <div style={{ 
                    display: 'grid', 
                    gridTemplateColumns: `repeat(${columnCount}, 1fr)`,
                    gap: '16px'
                  }}>
                    {renderFormFields()}
                  </div>
                  <Form.Item>
                    <div style={{ marginBottom: 16 }}>
                      <CalcControls
                        onCalculate={onCalculate}
                        onReset={onReset}
                        exportComponent={exportComponent}
                        disabled={isCalculating}
                      />
                        
                    </div>
                  </Form.Item>
                </Form>
              </Card>
            </div>
            
            {/* 分隔条 */}
            <div
              ref={splitterRef}
              onMouseDown={handleMouseDown}
              style={{
                width: '8px',
                background: isHovering ? '#1677ff' : '#f0f0f0',
                cursor: 'col-resize',
                position: 'relative',
                transition: 'background 0.2s ease',
                borderLeft: '1px solid #e8e8e8',
                borderRight: '1px solid #e8e8e8',
              }}
              onMouseEnter={() => setIsHovering(true)}
              onMouseLeave={() => setIsHovering(false)}
            />
            {/* 结果卡片 */}
            <div style={{ width: `${100 - splitRatio}%`, overflow: 'auto' }}>
              <Card title={`${title}结果`} style={{ height: '100%', marginLeft: '4px' }}>
                <Table
                  dataSource={result}
                  columns={columns}
                  pagination={false}
                  bordered
                  rowKey="key"
                  scroll={{ y: tableHeight }}
                />
              </Card>
            </div>
          </div>
        )}
      </div>
    );
  };

export default CalculationCard;